package com.yan.controller;

import com.yan.common.dto.LoginDto;
import com.yan.common.dto.RegisterDto;
import com.yan.common.util.AjaxEntity;
import com.yan.common.util.EmailUtil;
import com.yan.common.util.RedisUtils;
import com.yan.entity.User;
import com.yan.service.UserService;
import com.yan.service.comonService.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * UserController
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author 烟尘
 * @since 2025-06-20
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MailService mailService;

    @Value("${admin.adminEmail}")
    private String adminEmail;

    @PostMapping("/login")
    public AjaxEntity<Object> login(@Valid @RequestBody LoginDto loginDto) {
        log.info("用户登录：{}", loginDto);
        User user = userService.login(loginDto);
        return AjaxEntity.success("登录成功", user);
    }

    @PostMapping("/register")
    public AjaxEntity<Object> register(@Valid @RequestBody RegisterDto registerDto) {
        log.info("用户注册：{}", registerDto);
        userService.register(registerDto);
        return AjaxEntity.success("注册成功");
    }

    /**
     * 获取邮箱验证码
     * @param email 用户邮箱
     * @return 邮箱验证码
     */
    @GetMapping("/getEmailCode")
    public AjaxEntity<Object> getEmailCode(@RequestParam String email) {
        if (!EmailUtil.isValidQQEmail(adminEmail)){
            return AjaxEntity.fail("请配置正确的系统邮箱（QQ邮箱）");
        }

        String emailCode = EmailUtil.getEmailCode();
        log.info("获取邮箱：{}，生成的验证码：{}", email,emailCode);

        // 向用户邮箱发送邮件
        mailService.sendHtmlMail(adminEmail, email, "邮箱验证码", emailCode);
        // 保存验证码
        redisUtils.set(email, emailCode, 30, TimeUnit.SECONDS);
        return AjaxEntity.success("获取成功", emailCode);
    }
}
